<template>
  <div class="loan-apply-container">
    <!-- 顶部导航栏 -->
    <div class="loan-apply-header">
      <div class="back-button" @click="goBack">
        <el-icon><ArrowLeft /></el-icon>
      </div>
      <div class="header-title">申请借款</div>
      <div class="placeholder"></div>
    </div>

    <!-- 贷款申请表单 -->
    <div class="loan-apply-content">
      <el-form :model="formData" :rules="rules" ref="loanFormRef" label-position="top">
        <!-- 借款信息 -->
        <div class="form-section">
          <div class="section-title">输入借款信息</div>
          
          <!-- 借款金额 -->
          <el-form-item label="借款金额" prop="amount">
            <el-input-number 
              v-model="formData.amount" 
              :min="1000" 
              :max="300000" 
              :step="1000"
              controls-position="right"
              class="full-width"
            />
          </el-form-item>
          
          <!-- 借款期限 -->
          <el-form-item label="借款期限" prop="period">
            <el-select v-model="formData.period" placeholder="请选择借款期限" class="full-width">
              <el-option label="3个月" :value="3" />
              <el-option label="6个月" :value="6" />
              <el-option label="12个月" :value="12" />
              <el-option label="24个月" :value="24" />
              <el-option label="36个月" :value="36" />
            </el-select>
          </el-form-item>
          
          <!-- 每月还款 -->
          <div class="info-item">
            <span class="info-label">每月还款</span>
            <span class="info-value">¥ {{ monthlyPayment }} <span class="info-desc">(含日利率 0.02% ¥{{ interestPerMonth }})</span></span>
          </div>
          
          <!-- 选择银行卡 -->
          <el-form-item label="选择银行卡" prop="bankCardId">
            <el-input 
              v-model="selectedBankCardDisplay" 
              readonly 
              placeholder="请选择银行卡" 
              @click="showBankCardSelector"
              style="cursor: pointer;"
            />
          </el-form-item>
          
          <!-- 贷款用途 -->
          <el-form-item label="贷款用途" prop="purpose">
            <el-input
              v-model="formData.purpose"
              type="textarea"
              :rows="3"
              placeholder="请输入贷款用途，最多150字"
              maxlength="150"
              show-word-limit
            />
          </el-form-item>
        </div>
        
        <!-- 银行卡选择器 -->
        <el-dialog
          v-model="bankCardDialogVisible"
          title="选择银行卡"
          width="90%"
          :close-on-click-modal="false"
        >
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="3" animated />
          </div>
          
          <div v-else-if="bankCards.length === 0" class="empty-container">
            <el-empty description="暂无银行卡">
              <el-button type="primary" @click="goToBankCardPage">
                银行卡管理
              </el-button>
            </el-empty>
          </div>
          
          <div v-else class="bank-cards-list">
            <div 
              v-for="card in bankCards" 
              :key="card.id" 
              class="bank-card-item"
              :class="{ 'is-selected': formData.bankCardId === card.id }"
              @click="selectBankCard(card)"
            >
              <div class="bank-card-info">
                <div class="bank-name">{{ card.bankName }}</div>
                <div class="card-no">{{ formatCardNo(card.cardNo) }}</div>
                <div class="card-type">
                  {{ card.cardType === 0 ? '储蓄卡' : '信用卡' }}
                </div>
              </div>
              <div class="bank-card-select">
                <el-icon v-if="formData.bankCardId === card.id"><Check /></el-icon>
              </div>
            </div>
          </div>
        </el-dialog>
        
        <!-- 提交按钮 -->
        <div class="submit-section">
          <el-checkbox v-model="formData.agreement" class="agreement-checkbox">
            我已同意
          </el-checkbox>
          <el-button 
            type="primary" 
            class="submit-button" 
            :disabled="!formData.agreement" 
            @click="submitLoanApplication"
          >
            提交借款申请
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowLeft, Check } from '@element-plus/icons-vue';
import { useUserStore, useLoanStore,useBankCardStore } from '@/store';
import bankService from '@/services/bankService';
import loanService from '@/services/loanService';

const router = useRouter();
const userStore = useUserStore();
const loanStore = useLoanStore();
const bankCardStore = useBankCardStore();



// 表单引用
const loanFormRef = ref(null);

// 表单数据
const formData = ref({
  amount: loanStore.state.applyData.amount || 50000,
  period: loanStore.state.applyData.period || 12,
  bankCardId: loanStore.state.selectBankCardId || null,
  purpose: '',
  agreement: false
});

// 表单验证规则
const rules = {
  amount: [
    { required: true, message: '请输入借款金额', trigger: 'blur' },
    { type: 'number', min: 1000, max: 300000, message: '借款金额在1000-300000之间', trigger: 'blur' }
  ],
  period: [
    { required: true, message: '请选择借款期限', trigger: 'change' }
  ],
  bankCardId: [
    { required: true, message: '请选择银行卡', trigger: 'change' }
  ],
  purpose: [
    { required: true, message: '请输入贷款用途', trigger: 'blur' },
    { max: 150, message: '贷款用途不能超过150字', trigger: 'blur' }
  ]
};

// 银行卡相关
const bankCards = ref([]);
const bankCardDialogVisible = ref(false);
const loading = ref(false);
const selectedBankCard = ref(null);

// 计算每月还款金额
const monthlyPayment = computed(() => {
  if (!formData.value.amount || !formData.value.period) return '0.00';
  
  // 简单计算，实际应该使用更复杂的公式
  const principal = formData.value.amount;
  const months = formData.value.period;
  const monthlyInterestRate = 0.0002 * 30; // 日利率0.02%转换为月利率
  
  // 等额本息计算公式
  const monthlyRate = monthlyInterestRate;
  const temp = Math.pow(1 + monthlyRate, months);
  const payment = principal * monthlyRate * temp / (temp - 1);
  
  return payment.toFixed(2);
});

// 计算每月利息
const interestPerMonth = computed(() => {
  if (!formData.value.amount) return '0.00';
  return (formData.value.amount * 0.0002 * 30).toFixed(2);
});

// 显示选中的银行卡信息
const selectedBankCardDisplay = computed(() => {
  if (selectedBankCard.value) {
    return `${selectedBankCard.value.bankName} ${formatCardNo(selectedBankCard.value.cardNo)}`;
  }
  return '';
});

// 格式化银行卡号
const formatCardNo = (cardNo) => {
  if (!cardNo) return '';
  return cardNo.replace(/(\d{4})(?=\d)/g, '$1 ');
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 获取用户银行卡列表
const fetchBankCards = async () => {
  try {
    //有限缓存获取银行卡列表
    if (bankCardStore.bankCards.length > 0) {
      bankCards.value = bankCardStore.bankCards;
      return;
    } else {
      loading.value = true;
      const userId = userStore.userId;
      const response = await bankService.getBankCards(userId);
      bankCards.value = response;
    }
  }finally {
    loading.value = false;
  }
};

// 显示银行卡选择器
const showBankCardSelector = () => {
  console.log('showBankCardSelector',bankCardDialogVisible.value);
  fetchBankCards();
  bankCardDialogVisible.value = true;
};

// 选择银行卡
const selectBankCard = async (card) => {
  try {
    await ElMessageBox.confirm(
      `确认选择 ${card.bankName} ${formatCardNo(card.cardNo)} 作为收款银行卡？`,
      '确认选择',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'info',
      }
    );
    
    selectedBankCard.value = card;
    formData.value.bankCardId = card.id;
    bankCardDialogVisible.value = false;
  } catch {
    // 用户取消选择，不做任何操作
  }
};

// 跳转到银行卡页面
const goToBankCardPage = () => {
  router.push('/user/bank-card');
};

// 提交贷款申请
const submitLoanApplication = async () => {
  if (!formData.value.agreement) {
    ElMessage.warning('请先同意协议');
    return;
  }
  
  try {
    await loanFormRef.value.validate();
    
    const loanData = {
      productId: loanStore.state.productId,
      userId: userStore.userId,
      amount: formData.value.amount,
      period: formData.value.period,
      bankCardId: formData.value.bankCardId,
      purpose: formData.value.purpose
    };
    
    // 提交贷款申请
    const response = await loanService.applyLoan(loanData);
    // 跳转到申请成功页面，传递申请金额
    router.push({
      path: '/loan/success',
      query: {
        amount: formData.value.amount
      }
    });
  } catch (error) {
    ElMessage.error('贷款申请提交失败');
  }
};

// 页面加载时获取用户银行卡列表
onMounted(() => {
  fetchBankCards();
});
</script>

<style scoped>
.loan-apply-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
}

.loan-apply-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 50px;
  background-color: #3a4a7f;
  color: white;
  padding: 0 15px;
}

.back-button {
  font-size: 20px;
  cursor: pointer;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
}

.placeholder {
  width: 20px;
}

.loan-apply-content {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
}

.form-section {
  background-color: white;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.full-width {
  width: 100%;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin: 15px 0;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.info-label {
  color: #666;
}

.info-value {
  font-weight: bold;
}

.info-desc {
  font-size: 12px;
  color: #999;
  font-weight: normal;
}

.bank-cards-list {
  max-height: 300px;
  overflow-y: auto;
}

.bank-card-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
}

.bank-card-item:hover {
  background-color: #f5f7fa;
}

.bank-card-item.is-selected {
  background-color: #ecf5ff;
}

.bank-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.card-no {
  color: #666;
  margin-bottom: 5px;
}

.card-type {
  font-size: 12px;
  color: #999;
}

.submit-section {
  margin-top: 20px;
  text-align: center;
}

.agreement-checkbox {
  margin-bottom: 15px;
}

.submit-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
}

.loading-container, .empty-container {
  padding: 20px;
  text-align: center;
}
</style>